package com.atguigu.yygh.hosp.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.ScheduleQueryVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    private ScheduleRepository scheduleRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private DepartmentService departmentService;

    @Override
    public void save(Schedule schedule) {
        if (schedule == null) {
            throw new YyghException(20001, "schedule参数错误");
        }

        //根据医院编号 和 排班编号查询
        Schedule scheduleExist = scheduleRepository.
                getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
        //判断
        if (scheduleExist != null) {
            scheduleExist.setUpdateTime(new Date());
            scheduleExist.setIsDeleted(0);
            scheduleExist.setStatus(1);
            scheduleRepository.save(scheduleExist);
        } else {
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
            scheduleRepository.save(schedule);

        }

    }

    @Override
    public Page<Schedule> selectPage(int page, int limit, ScheduleQueryVo scheduleQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //0为第一页
        Pageable pageable = PageRequest.of(page - 1, limit, sort);
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo, schedule);
        schedule.setIsDeleted(0);
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写
        //创建实例
        Example<Schedule> example = Example.of(schedule, matcher);
        Page<Schedule> pages = scheduleRepository.findAll(example, pageable);
        return pages;
    }

    @Override
    public void remove(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (null != schedule) {
            schedule.setIsDeleted(1);
            scheduleRepository.save(schedule);
//            scheduleRepository.deleteById(schedule.getId());
        }
    }

    //根据医院编号 和 科室编号 ，查询排班规则数据
    @Override
    public Map<String, Object> getRuleSchedule(long page, long limit, String hoscode, String depcode) {
        //1 封装条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        //2 封装聚合部分
        Aggregation agg = Aggregation.newAggregation(
                //2.1条件匹配
                Aggregation.match(criteria),
                //2.2根据workDate分组
                Aggregation.group("workDate")
                        .first("workDate")
                        .as("workDate")
                //2.3统计数量操作 出诊医生数量
                        .count().as("docCount")
                //2.4求和操作 号源数量
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                //2.5排序
                Aggregation.sort(Sort.Direction.ASC,"workDate"),
                //2.6分页
                Aggregation.skip((page-1)*limit),
                Aggregation.limit(limit)
        );
        //调用方法得到结果
        AggregationResults<BookingScheduleRuleVo>
                aggregate =
                mongoTemplate.aggregate
                        (agg, Schedule.class, BookingScheduleRuleVo.class);

        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggregate.getMappedResults();
        //上面bookingScheduleRuleVoList有查询出来的所有排班日期 没有星期几数据
        //根据workDate日期获取对应星期几
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            //获取workDate
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            //调用方法，得到日期workDate对应 星期几
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            //把星期dayOfWeek放到对象里
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }
         //获取查询有多少条记录，实现分页
        Aggregation aggTotal = Aggregation.newAggregation(
                //2.1条件匹配
                Aggregation.match(criteria),
                //2.2根据workDate分组
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> aggregate1Total = mongoTemplate
                .aggregate(aggTotal, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> list = aggregate1Total.getMappedResults();
        int total = list.size();


        //设置最终数据，进行返回
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList",bookingScheduleRuleVoList);
        result.put("total",total);
        //获取医院名称
       String hosName = hospitalService.getHosNameByHoscode(hoscode);
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname",hosName);
        result.put("baseMap",baseMap);
        return result;
    }
    //查询日期下面医生详情信息
    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        //日期格式 String ->  Date

        List<Schedule> list=
                scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode,depcode, new DateTime(workDate).toDate());
        //封装医院名称和科室名称
        list.stream().forEach(item->{
            this.packSchedule(item);
        });
        return list;
    }
    //封装医院名称和科室名称
    private void packSchedule(Schedule schedule) {
        //获取医院名称
        String hosName = hospitalService.getHosNameByHoscode(schedule.getHoscode());
        //获取科室名称
        String depName = departmentService.getDepName(schedule.getDepcode());
      //放到Schedule得属性param map集合
        Map<String, Object> param = schedule.getParam();
        param.put("hosname",hosName);
        param.put("depname",depName);
        //根据工作日期得到对应星期
        Date workDate = schedule.getWorkDate();
        String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
        param.put("dayOfWeek",dayOfWeek);
    }


    /**
     * 根据日期获取周几数据
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }


}
